package com.sniff.atp.service.login;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.sniff.atp.constant.RedisPrefix;
import com.sniff.atp.dto.ClientLoginDTO;
import com.sniff.atp.dto.ContentDTO;
import com.sniff.atp.dto.customer.CustomerDTO;
import com.sniff.atp.dto.request.UserInfo;
import com.sniff.atp.enums.api.CustomerAPI;
import com.sniff.atp.manage.RedisManage;
import com.sniff.atp.utils.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class ClientLoginService {
    @Autowired
    private RedisManage redisManage;

    public ClientLoginDTO login(String nameOrEmail, String password) {
        JSONObject params = JsonUtil.readJson("ClientLogin.json");
        params.put("nameOrEmail", nameOrEmail);
        params.put("password", DigestUtils.md5Hex(password));
        String result = new HttpClientUtil().doPostJson(CustomerAPI.CLIENT_LOGIN.getApi(), params);
        ClientLoginDTO clientLoginDTO = new ClientLoginDTO();
        clientLoginDTO.setToken(JsonUtil.extractString(result, "data.token"));
        clientLoginDTO.setShopId(JsonUtil.extractString(result, "data.customerShopList[0].customerShopId"));
        clientLoginDTO.setSystemSource(JsonUtil.extractString(result, "data.customerRespDTO.systemSource"));
        clientLoginDTO.setStationCode(JsonUtil.extractString(result, "data.customerRespDTO.stationCode"));
        return clientLoginDTO;
    }

    public ClientLoginDTO loginNew(String nameOrEmail, String password) {
        JSONObject params = JsonUtil.readJson("ClientLogin.json");
        params.put("nameOrEmail", nameOrEmail);
        params.put("password", password);
        String result = new HttpClientUtil().doPostJson(CustomerAPI.CLIENT_LOGIN.getApi(), params);
        ClientLoginDTO clientLoginDTO = new ClientLoginDTO();
        clientLoginDTO.setToken(JsonUtil.extractString(result, "data.token"));
        clientLoginDTO.setShopId(JsonUtil.extractString(result, "data.customerShopList[0].customerShopId"));
        clientLoginDTO.setSystemSource(JsonUtil.extractString(result, "data.customerRespDTO.systemSource"));
        clientLoginDTO.setStationCode(JsonUtil.extractString(result, "data.customerRespDTO.stationCode"));
        return clientLoginDTO;
    }

    public ClientLoginDTO changeLogin(ClientLoginDTO clientLoginDTO) {
        String result = new HttpClientUtil(Headers.setClientHeader(clientLoginDTO)).doPostJson(CustomerAPI.CHANGE_LOGIN.getApi(), null);
        clientLoginDTO.setToken(JsonUtil.extractString(result, "data.token"));
        clientLoginDTO.setShopId(JsonUtil.extractString(result, "data.customerShopList[0].customerShopId"));
        clientLoginDTO.setSystemSource(JsonUtil.extractString(result, "data.customerRespDTO.systemSource"));
        return clientLoginDTO;
    }

    /**
     * 切换登录平台
     * @param clientLoginDTO
     * @param type
     * @return
     */
    public ClientLoginDTO changeLoginByType(ClientLoginDTO clientLoginDTO, String type) {
        Map<String, String> params = new HashMap<>();
        params.put("type", type);
        String result = new HttpClientUtil(Headers.setClientHeader(clientLoginDTO)).doGet(CustomerAPI.CHANGE_LOGIN_BY_TYPE.getApi(), params);
        clientLoginDTO.setToken(JsonUtil.extractString(result, "data.token"));
        clientLoginDTO.setShopId(JsonUtil.extractString(result, "data.customerShopList[0].customerShopId"));
        clientLoginDTO.setSystemSource(JsonUtil.extractString(result, "data.customerRespDTO.systemSource"));
        clientLoginDTO.setStationCode(JsonUtil.extractString(result, "data.customerRespDTO.stationCode"));
        return clientLoginDTO;
    }

    /**
     * 根据店铺名称获取店铺id
     * @param clientLoginDTO
     * @param customerShopName
     * @return
     */
    public String getCustomerShopId(ClientLoginDTO clientLoginDTO, String customerShopName) {
        //获取客户信息
        Map<String, String> params = new HashMap<>();
        params.put("token", clientLoginDTO.getToken());
        String result = new HttpClientUtil(Headers.setClientHeader(clientLoginDTO)).doGet(CustomerAPI.GET_CUSTOMER_DETAILS.getApi(), params);

        JSONArray customerShopList = JsonUtil.extractJSONArray(result, "data.customerShopList");
        String customerShopId = JsonUtil.findJSONArray(customerShopList, "customerShopName", customerShopName).getString("customerShopId");
        return customerShopId;
    }

    /**
     * 切换店铺
     * @param clientLoginDTO
     * @param customerShopId
     * @return
     */
    public void changeShop(ClientLoginDTO clientLoginDTO, String customerShopId) {
        //切换店铺
        Map<String, String> params = new HashMap<>();
        params.put("shopId", customerShopId);
        new HttpClientUtil(Headers.setClientHeader(clientLoginDTO)).doGet(CustomerAPI.CHANGE_SHOP.getApi(), params);
    }

    /**
     * 登录并切换店铺
     * @param userInfo
     * @return
     */
    public ClientLoginDTO loginByUserInfo(UserInfo userInfo) {
        String nameOrEmail = userInfo.getUserName();
        String password = userInfo.getPassword();
        String customerShopName = userInfo.getCustomerShopName();
        //登录
        ClientLoginDTO clientLoginDTO = login(nameOrEmail, password);

        //切换系统
        if(!clientLoginDTO.getSystemSource().equals(userInfo.getSystemSource()) && StringUtils.isNotEmpty(userInfo.getSystemSource())){
            clientLoginDTO = changeLoginByType(clientLoginDTO, userInfo.getSystemSource());
        }
        //切换店铺
        if(StringUtils.isBlank(customerShopName) || "null".equals(customerShopName)){
            return clientLoginDTO;
        }
        //根据店铺名称查询店铺id
        String customerShopId = getCustomerShopId(clientLoginDTO, customerShopName);
        changeShop(clientLoginDTO, customerShopId);
        clientLoginDTO.setShopId(customerShopId);
        return clientLoginDTO;
    }

    /**
     * 登录并切换店铺
     * @param customerShopName
     * @return
     */
    public ClientLoginDTO loginByCustomerShopName(String customerShopName) {
        //根据店铺名称查询店铺id
        String res =  DBUtil.selectOne("CUSTOMER-根据客户店铺名称查询用户信息",new ContentDTO("customerShopName",customerShopName),new ContentDTO("customerShopId",customerShopName)).toJSONString();
        String customerShopId = JsonUtil.extractString(res,"customer_shop_id");
        String systemSource = JsonUtil.extractString(res,"system_source");
        String loginName = JsonUtil.extractString(res,"login_name");
        String password = JsonUtil.extractString(res,"password");
        password = getNewPassword(password);
        //登录
        ClientLoginDTO clientLoginDTO = loginNew(loginName, password);
        //切换系统
        clientLoginDTO = changeLoginByType(clientLoginDTO, systemSource);
        //切换店铺
        changeShop(clientLoginDTO, customerShopId);
        clientLoginDTO.setShopId(customerShopId);
        return clientLoginDTO;
    }

    /**
     * 密码解密
     * @param password
     * @return
     */
    public String getNewPassword(String password) {
        // 密码比较
        Date date = new Date();
        Integer systemSource = 2;
        String customerPasswordRe = password.substring(0,password.length()-2);
        String newPassword = PasswordUtil.getEncryptionPassword(systemSource,customerPasswordRe+date.getHours(), null);
        return newPassword;
    }




    public String signUp(String username, String invitationCode, String countryPlaceCode){
        JSONObject params = JsonUtil.readJson("signup");
        params.replace("loginName", username);
        params.replace("customerName", username);
        params.replace("invitationCode", invitationCode);
        params.replace("countryPlaceCode", countryPlaceCode);


        String customerMobile = RandomUtil.numberStringNoZero(11);
        params.replace("customerMobile", customerMobile);

        String email = RandomStringUtils.random(3, "ABCDEFGHIJKLMNOPQRSTUVWXYZ") + DateUtil.longString() + "@qq.com";
        params.replace("customerEmail", email);

        code(email, countryPlaceCode);
        String key = RedisPrefix.SNIFF_EMIAL_CODE + email + ":";
        String verificationCode = redisManage.getKey(key);
        params.replace("verificationCode", verificationCode);
        return new HttpClientUtil().doPostJson(CustomerAPI.SIGN_UP.getApi(), params);
    }

    public String signUp(String mobile, String code, String countryPlaceCode, String invitationCode){
        JSONObject params = JsonUtil.readJson("signup");
        params.replace("invitationCode", invitationCode);
        params.replace("countryPlaceCode", countryPlaceCode);
        params.replace("customerMobile", mobile);
        params.replace("verificationCode", code);
        if (countryPlaceCode.equals("JP")){
            params.replace("countryCode", "+81");
        }else if (countryPlaceCode.equals("KR")){
            params.replace("countryCode", "+82");
        }else {
            params.replace("countryCode", "+44");
        }

        return new HttpClientUtil().doPostJson(CustomerAPI.SIGN_UP.getApi(), params);
    }

    public String code(String customerEmail, String countryPlaceCode){
        JSONObject params = new JSONObject();
        if(customerEmail.contains("@")){
            params.put("customerEmail", customerEmail);
            params.put("countryPlaceCode", countryPlaceCode);
            return new HttpClientUtil().doPostJson(CustomerAPI.CODE.getApi(), params);
        }else {
            params.put("customerMobile", customerEmail);

            if (countryPlaceCode.equals("JP")){
                params.put("globalRoaming", "+81");
            }else if (countryPlaceCode.equals("KR")){
                params.put("globalRoaming", "+82");
            }else {
                params.put("globalRoaming", "+44");
            }
            params.put("bizType", 1);
            params.put("countryPlaceCode", countryPlaceCode);
            return new HttpClientUtil().doPostJson(CustomerAPI.MOBILE_CODE.getApi(), params);
        }
    }

    public String code(String mobile){
        JSONObject params = new JSONObject();
        params.put("customerMobile", mobile);
        params.put("globalRoaming", "+86");
        params.put("bizType", 3);
        return new HttpClientUtil().doPostJson(CustomerAPI.MOBILE_CODE.getApi(), params);

    }

    public String systemSourceLogin(String uuid){
        JSONObject params = new JSONObject();
        params.put("uuid", uuid);
        params.put("systemSource", 1);
        return new HttpClientUtil().doPostJson(CustomerAPI.SYSTEM_SOURCES_LOGIN.getApi(), params);
    }

    public String shopAdd(String token, String customerShopName){
        JSONObject params = JsonUtil.readJson("shopAdd");
        params.replace("customerShopName", customerShopName);
        HashMap<String, String> headers = new HashMap<>();
        headers.put("X-AuthToken", token);
        return new HttpClientUtil(headers).doPostJson(CustomerAPI.SHOP_ADD.getApi(), params);
    }

    public String login(String nameOrEmail){
        JSONObject params = JsonUtil.readJson("ClientLogin.json");
        params.put("nameOrEmail", nameOrEmail);
        params.put("password", DigestUtils.md5Hex("test123456"));
        return new  HttpClientUtil().doPostJson(CustomerAPI.CLIENT_LOGIN.getApi(), params);
    }

    public String mobileLogin(String mobile, String countryPlaceCode,String code){
        JSONObject params = JsonUtil.readJson("mobileLogin.json");
        params.replace("customerMobile", mobile);
        params.replace("verificationCode", code);

        if (countryPlaceCode.equals("JP")){
            params.replace("globalRoaming", "+81");
            params.replace("countryCode", "+81");
        }else if (countryPlaceCode.equals("KR")){
            params.replace("globalRoaming", "+82");
            params.replace("countryCode", "+82");
        }else {
            params.replace("globalRoaming", "+44");
            params.replace("countryCode", "+44");
        }


        return new  HttpClientUtil().doPostJson(CustomerAPI.MOBILE_LOGIN.getApi(), params);
    }


    //通过用户信息查询客户id
    public String qryCustomerInfo(String username,String customerShopId,String systemType){

        String res =  DBUtil.selectOne("CUSTOMER-根据账号查询客户基本信息",new ContentDTO("username",username),new ContentDTO("customerShopId",customerShopId),new ContentDTO("systemType",systemType)).toJSONString();
        String customerId = JsonUtil.extractString(res,"customer_id");
        return customerId;
    }

    //通过用户信息查询客户supercustomerId
    public String qrySuperCustomerInfo(CustomerDTO customerDTO){

        String qrySql = null;
        //按不同的入参，转换成不同的sql
        if(customerDTO.getCustomerShopId() != null && StringUtils.isNotEmpty(customerDTO.getCustomerShopId())){
            qrySql = "SELECT t1.* FROM sniff_customer t1 left join sniff_customer_shop t2 on t1.customer_id = t2.customer_id " +
                    "where t2.customer_shop_id = '" + customerDTO.getCustomerShopId() +
                    "' and t1.system_source = '" + customerDTO.getSystemType() + "' limit 1";
        }else if(customerDTO.getLoginName() != null && StringUtils.isNotEmpty(customerDTO.getLoginName())){
            qrySql = "SELECT t1.* FROM sniff_customer t1 left join sniff_customer_shop t2 on t1.customer_id = t2.customer_id " +
                    "where t1.login_name = '" + customerDTO.getLoginName() +
                    "' and t1.system_source = '" + customerDTO.getSystemType() + "' limit 1";
        }else if(customerDTO.getCustomerMobile() != null && StringUtils.isNotEmpty(customerDTO.getCustomerMobile())){
            qrySql = "SELECT t1.* FROM sniff_customer t1 left join sniff_customer_shop t2 on t1.customer_id = t2.customer_id " +
                    "where t1.customer_mobile = '" + customerDTO.getCustomerMobile() +
                    "' and t1.system_source = '" + customerDTO.getSystemType() + "' limit 1";
        }

        System.out.println(qrySql);
        String res =  DBUtil.selectOne("CUSTOMER-公共传入sql查询",new ContentDTO("", qrySql)).toJSONString();
        String superCustomerId = JsonUtil.extractString(res,"super_customer_id");
        return superCustomerId;
    }
    //通过用户信息查询客户customerId
    public String qryCustomerInfoMix(CustomerDTO customerDTO){

        String qrySql = null;
        //按不同的入参，转换成不同的sql
        if(customerDTO.getCustomerShopId() != null && StringUtils.isNotEmpty(customerDTO.getCustomerShopId())){
            qrySql = "SELECT t1.* FROM sniff_customer t1 left join sniff_customer_shop t2 on t1.customer_id = t2.customer_id " +
                    "where t2.customer_shop_id = '" + customerDTO.getCustomerShopId() +
                    "' and t1.system_source = '" + customerDTO.getSystemType() + "' limit 1";
        }else if(customerDTO.getLoginName() != null && StringUtils.isNotEmpty(customerDTO.getLoginName())){
            qrySql = "SELECT t1.* FROM sniff_customer t1 left join sniff_customer_shop t2 on t1.customer_id = t2.customer_id " +
                    "where t1.login_name = '" + customerDTO.getLoginName() +
                    "' and t1.system_source = '" + customerDTO.getSystemType() + "' limit 1";
        }else if(customerDTO.getCustomerMobile() != null && StringUtils.isNotEmpty(customerDTO.getCustomerMobile())){
            qrySql = "SELECT t1.* FROM sniff_customer t1 left join sniff_customer_shop t2 on t1.customer_id = t2.customer_id " +
                    "where t1.customer_mobile = '" + customerDTO.getCustomerMobile() +
                    "' and t1.system_source = '" + customerDTO.getSystemType() + "' limit 1";
        }

        System.out.println(qrySql);
        String res =  DBUtil.selectOne("CUSTOMER-公共传入sql查询",new ContentDTO("", qrySql)).toJSONString();
        String customerId = JsonUtil.extractString(res,"customer_id");
        return customerId;
    }

    //通过用户信息查询客户id
    public String qryCustomerInfoSupercustomerId(String username,String customerShopId,String systemType){

        String res =  DBUtil.selectOne("CUSTOMER-根据账号查询客户基本信息",
                new ContentDTO("username",username),
                new ContentDTO("customerShopId",customerShopId),
                new ContentDTO("systemType",systemType)
        ).toJSONString();
        String superCustomerId = JsonUtil.extractString(res,"super_customer_id");
        return superCustomerId;
    }

    //通过客户id更新余额
    public String addAvaliableAmount(String customerId){

        DBUtil.insertOrUpdate("SETTLEMENT-根据客户id更新用户余额",new ContentDTO("customerId",customerId) );
        return customerId;
    }

    //通过超级id更新直营商城余额
    public String addAvaliableAmount2D(String customerId){

        DBUtil.insertOrUpdate("SETTLEMENT-根据客户超级编号更新用户余额",new ContentDTO("customerId",customerId) );
        return customerId;
    }

    //通过客户店铺id更新余额
    public String addAvaliableAmountByShopid(String superCustomerId){

        DBUtil.insertOrUpdate("SETTLEMENT-根据客户店铺id更新用户余额",new ContentDTO("customerId",superCustomerId) );
        return superCustomerId;
    }

    //通过supercustomerId修改会员等级
    public void changeMembershipLvl(String superCustomerId,String membershipTemplateId){

        DBUtil.insertOrUpdate("SETTLEMENT-修改会员等级",new ContentDTO("superCustomerId",superCustomerId),new ContentDTO("membershipTemplateId",membershipTemplateId) );
    }

    //获取验证码
    public String getCode(String customerMobile){
        if(customerMobile == null || customerMobile == ""){
            return "请输入手机号或者邮箱";
        } else if (customerMobile.contains("@")) {
            //获取邮箱验证码
            String key = RedisPrefix.SNIFF_EMIAL_CODE + customerMobile + ":";
            String verificationCode = redisManage.getKey(key);
            return verificationCode;
        }
        //获取手机验证码
        String res = DBUtil.selectOne("获取手机验证码",new ContentDTO("",customerMobile)).toJSONString();
        return JsonUtil.extractString(res,"sms_content");
    }
}
